/**
 * Created by tdzl2003 on 6/18/16.
 */

import { AsyncStorage } from 'react-native';
import { EventEmitter } from 'fbemitter';
import URI from 'urijs';

const RPC = new EventEmitter();
const emit = RPC.emit.bind(RPC);
export default RPC;

const KEY_TOKEN = 'accessToken';
const ROOT_URL = 'http://api.your.site/';

let token = null;

export function getToken() {
  return token;
}

export function saveToken(_token) {
  token = _token;
  return AsyncStorage.setItem(KEY_TOKEN, token);
}

export async function loadToken() {
  token = await AsyncStorage.getItem(KEY_TOKEN);
  return token;
}

export async function clearToken() {
  await AsyncStorage.removeItem(KEY_TOKEN);
  token = null;
}

async function request(url, _options) {
  const uri = new URI(ROOT_URL + url);
  if (token) {
    uri.addQuery('Authorize', token);
  }

  const options = _options || {};
  options.method = options.method || 'GET';
  options.headers = options.headers || {};

  if (__DEV__) {
    console.log(`${options.method} ${uri}`);
    if (options.body) {
      console.log(options.body);
    }
  }

  const resp = await fetch(uri.toString(), options);
  const text = await resp.text();
  console.log('RESP:', text);
  const json = JSON.parse(text);

  // 如果请求失败
  if (resp.status !== 200) {
    if (resp.status === 401) {
      // HTTP 401 表示授权验证失败(通常是token已过期)
      emit('invalidToken');
    }

    const err = new Error(json.message);
    err.code = resp.status;
    err.origin = json;
    throw err;
  }
  return json.content;
}

export function get(url, options) {
  return request(url, options);
}

export function post(url, data, options) {
  return request(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
    ...options,
  });
}
